import json

from shop.model.goods import Goods
from shop.model.user_browse import UserBrowse
from shop.util.miaoyouquan_operation import MiaoHandler
from shop.util.mylogger import KLogger, Alogger
from shop.util.num_operation import NumOper
from shop.util.redis_util import RedisUtil
from shop.util.time_operation import TimeClass


class BrowseHandler:
    '''
    浏览记录操作类
    '''

    def __init__(self, user_id, goods_info=None):
        self.user_id = user_id
        self.goods_info = goods_info

    def save_browse(self):
        '''
        保存浏览记录
        :return:
        '''
        if not self.goods_info:
            raise Exception("goods can't be null")
        goods_info_dict = json.loads(self.goods_info)
        goods_id = goods_info_dict.get("goodsId")
        # 保存商品信息
        Goods.save_goods(goods_id, self.goods_info)
        # 保存用户浏览记录
        UserBrowse.save_one_user_browse_record(self.user_id, goods_id)

    def get_browse(self, page, page_size):
        '''
        获取浏览记录
        :return:
        '''
        KLogger.debug(page)
        KLogger.debug(page_size)
        some_ub, total_num = UserBrowse.get_one_user_browse_record(self.user_id, page, page_size)
        # 得到所有的goods_id列表
        goods_id_list = []
        goods_id_create_time_dict = {}
        for ub in some_ub:
            create_time = ub.create_time
            goods_id = ub.goods_id
            goods_id_create_time_dict[goods_id] = TimeClass.get_str_by_datetime(create_time)
            goods_id_list.append(goods_id)

        # 根据goods_id获取所有的商品
        some_goods = Goods.get_goods_by_goods_id_list(goods_id_list)
        goods_id_dict_goods_dict = {}
        for one_goods in some_goods:
            one_goods_id = one_goods.goods_id
            goods_id_dict_goods_dict[one_goods_id] = one_goods
        KLogger.debug("根据商品id_list,查到的商品数量:{}".format(len(some_goods)))
        # 重新格式化结果
        res = []
        for one_goods_id in goods_id_list:
            one_goods = goods_id_dict_goods_dict.get(one_goods_id)
            json_goods = one_goods.to_json()
            goods_id = one_goods.goods_id
            json_goods["view_time"] = goods_id_create_time_dict.get(goods_id)
            res.append(json_goods)
        return {
            "goods": res,
            "total": total_num
        }


class RushBugHandler:
    def __init__(self, taoqianggou_params=None, page=None, item_type="", page_size=10):
        self.taoqianggou_params = taoqianggou_params
        self.page = page
        self.redis_key = "rushbug_page_str_" + str(page) + str(item_type) + str(page_size)
        self.ru = RedisUtil()
        self.page_rediskey = "rushbug_page_hash" + str(item_type) + str(page_size)
        self.expire_seconds = 60 * 60 * 24

    def get_res(self):
        """
        获取结果
        :return:
        """
        # 首先从redis中获取缓存，如果获取不到就执行请求第三方接口
        redis_res = self.ru.get_str(self.redis_key)
        if redis_res:
            Alogger.info("精选模块使用了缓存，redis_key是：{}".format(self.redis_key))
            new_data = json.loads(redis_res)
        else:
            data = self.get_request_taoqiaogou_res()
            new_data = self.format_data(data)
        return new_data

    def get_random_pagenum(self, one_pagenum):
        """
        获取随机页码数
        :return:
        """
        # 判断是否需要设置过期时间
        need_expire = False
        if not self.ru.get_hash_len(self.page_rediskey):
            # 如果这个hash长度为0，则表示是第一次设置，需要给他设置过期时间
            need_expire = True
        # 根据传来的页数从redis中获取对应的页数，如果没有，则重新生成
        hash_res_page = self.ru.get_hash_one_key(self.page_rediskey, str(one_pagenum))
        if not hash_res_page:
            hash_res_page = str(NumOper.get_random_sed_num(one_pagenum))
            self.ru.set_hash(self.page_rediskey, {str(one_pagenum): str(hash_res_page)})
        # 判断是否需要设置过期时间
        if need_expire:
            self.ru.expire_reids_key(self.page_rediskey, self.expire_seconds)
        return int(hash_res_page)

    def check_params_none(self):
        """
        校验参数是否为none，为none则剔除;添加随机返回页数的功能
        :return:
        """
        for key, value in dict(self.taoqianggou_params).items():
            if not value:
                self.taoqianggou_params.pop(key)
            # 获取随机页数
            # if key == "page":
            # 首先判断这个页数是否存在
            # self.taoqianggou_params[key] = self.get_random_pagenum(self.taoqianggou_params[key])

    def get_request_taoqiaogou_res(self):
        """
        请求淘抢购的喵有券接口
        :return:
        """
        self.check_params_none()
        mh = MiaoHandler()
        Alogger.debug(self.taoqianggou_params)
        res = mh.req_taoqianggou_juhuasuan_get(**self.taoqianggou_params)
        return res.get("data")

    def format_data(self, data):
        """
        把返回的data值转化为
        :param data:list
        :return:
        """
        # ju_list = []
        # tqg_list = []
        # for index, one_data in enumerate(data):
        #     item_type = one_data.get('item_type')
        #     # 筛选出5个聚划算商品
        #     if item_type == "ju" and len(ju_list) < 5:
        #         ju_list.append(one_data)
        #         data.remove(one_data)
        #     # 筛选出5个淘抢购商品
        #     if item_type == "tqg" and len(tqg_list) < 5:
        #         tqg_list.append(one_data)
        #         data.remove(one_data)
        new_data = data
        # 把结果设置进redis中，缓存一天
        self.ru.set_str(self.redis_key, json.dumps(new_data), expire_second=60 * 60 * 24)
        return new_data
